from apps.common.base.views import *

from .service import *
from .serializers import *
from apps.common.utils import time
from apps.common.utils.utils import random_str
import datetime

class FileViewSet(BaseViewSet):

    '''上传图片'''
    @action(methods=['post'], detail=False, url_path='uploadImage',authentication_classes=[],permission_classes=[])
    def uploadImageAPI(self, request):
        params = getRequestParams(request)
        # 获取前端传递的image文件
        fp = None
        fileType = ''
        filePath = str(datetime.datetime.now().year) + '/' + str(datetime.datetime.now().month) + '/' + str(datetime.datetime.now().day)
        
        if request.FILES.get('file'):
            fp = request.FILES.get('file')
            fileName = random_str(8) + (fp.name[-20:] if len(fp.name)>20 else fp.name)
            if fp.size > 1024*1024*500:
                return Response(response_message('大于500M，不允许上传'))
            if fp.content_type.find('image') >= 0:
                fileType = 'image'
            elif fp.content_type.find('video') >= 0:
                fileType = 'video'
            elif fp.content_type.find('audio') >= 0:
                fileType = 'audio'
            else:
                return Response(response_message('文件格式非法'))
            print('fp', fp.name, fp.content_type)
            
        else:
            return Response(response_message('文件为空'))

        print('clientname', params.get('clientname'))
        bucket = None
        if params.get('clientname'):
            bucket = params.get('clientname').replace('_', '')
        else:
            bucket = 'file'
        
        print('参数', fp, bucket, filePath, fileName, fileType, fp.size)
        
        # 将文件路径存到数据库
        image = File.objects.create(**{'fileName': uploadFile(fp, bucket, filePath, fileName), 'baseImgUrl': baseImgUrl, 'fileType': fileType, 'fileSize': fp.size})
        return Response(response_success_notScrypt({'image': {'id': image.id, 'baseImgUrl': image.baseImgUrl, 'fileName': image.fileName, 'fileType': image.fileType}}))